package com.jx.lcs.integral.web;

import java.io.IOException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jx.lcs.integral.entity.UserIntegral;
import com.jx.lcs.integral.service.UserIntegralService;
import com.jx.lcs.integral.service.IntegralTypeService;
import com.tianyu.jty.common.persistence.Page;
import com.tianyu.jty.common.utils.DateUtils;
import com.tianyu.jty.common.web.BaseController;

/** 
 * 用户controller
 * @author JiaYY 
 * @date 2015年8月25日
 */
@Controller
@RequestMapping("userIntegral")
public class UserIntegralController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(UserIntegralController.class);

	@Autowired
	private UserIntegralService userIntegralService;
	
	@Autowired
	private IntegralTypeService integralTypeService;
	
	/**
	 * 默认页面
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "userintegral/userIntegralList";
	}
	
	/**
	 * 获取用户积分列表json
	 */
	@RequestMapping(value="json",method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> userIntegralList(HttpServletRequest request) {
		try{
			Page<UserIntegral> page = getPage(request);
			page = userIntegralService.findUserIntegralList(page, request);
			return getEasyUIData(page);
		}catch(Exception e){
			logger.error("--获取用户积分列表出现异常！", e);
			return null;
		}
	}
	
	/**
	 * 查看用户积分明细
	 * 
	 * @param uid
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "detailList/{uid}", method = RequestMethod.GET)
	public String detailList(@PathVariable("uid") String uid, Model model) {
		model.addAttribute("uid", uid);
		return "userintegral/integralDetailList";
	}
	
	/**
	 * 获取用户积分明细json
	 */
	@RequestMapping(value="userIntegralDetail",method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> userIntegralDetail(HttpServletRequest request) {
		try{
			Page<UserIntegral> page = getPage(request);
			page = userIntegralService.findUserIntegralDetail(page, request);
			return getEasyUIData(page);
		}catch(Exception e){
			logger.error("--获取用户积分明细出现异常！", e);
			return null;
		}
	}
	
	/**
	 * 补用户积分
	 * 
	 * @return
	 */
	@RequestMapping(value = "addIntegralBetach", method = RequestMethod.GET)
	public String addIntegralBetach() {
		List<Object[]> list = userIntegralService.addIntegralBetach();
		Object[] obj = null;
		
		if(list != null && list.size() > 0) {
			UserIntegral userIntegral = null;
			for(int i=0; i<list.size(); i++) {
				obj = list.get(i);
				
				userIntegral = new UserIntegral();
				userIntegral.setSourceCode((String)obj[0]);
				userIntegral.setUid((String)obj[1]);
				String title = "成功获客（"+(String)obj[2]+"）";
				userIntegral.setTitle(title);
				userIntegral.setSource("4");
				userIntegral.setScore(50);
				userIntegral.setIncomeType("0");
				Timestamp  t =(Timestamp)(obj[3]);
				userIntegral.setRecordTime(new Date(t.getTime()));
				userIntegralService.save(userIntegral);
				
			}
		}
		return "增加积分成功";
	}
	
	/**
	 * 报表导出
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "export", method = RequestMethod.GET, produces = "text/plain;charset=utf-8")
	@ResponseBody
	public void export(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String beginDate = request.getParameter("beginDate");
		String endDate = request.getParameter("endDate");
		
		if (StringUtils.isBlank(endDate)) {
			endDate = DateUtils.getDate();
		}
		
		String endStr = DateUtils.formatDate(DateUtils.parseDate(endDate), "yyyyMMdd");
		String fileName = "-" + endStr;
		if(!StringUtils.isBlank(beginDate)) {
			String beginStr = DateUtils.formatDate(DateUtils.parseDate(beginDate), "yyyyMMdd");
			
			fileName = beginStr + "-" + endStr;
		}
		
		endDate = DateUtils.addDays(endDate, 1);
		
		response.setContentType("text/html;charset=utf-8");
		response.setContentType("application/x-msdownload;");
		response.setHeader("Content-disposition", "attachment; filename="
				+ URLEncoder.encode("用户积分数据" + fileName, "UTF-8") + ".xls");

		userIntegralService.exportUserIntegral(request,
				response.getOutputStream());
	}
	
	/**
	 * 积分兑换 
	 * @return
	 */
	@RequestMapping(value = "useIntegralBetach", method = RequestMethod.GET)
	public String useIntegralBetach(HttpServletRequest request) {
		try {
			List<UserIntegral> list = userIntegralService.findUserRestIntegralAll(request);
			if(list != null && list.size() > 0) {
				UserIntegral integral = null;
				int lowScore = 100;
				for(UserIntegral userIntegral : list) {
					if(userIntegral.getRestScore() >= lowScore) {
						//计算红包兑换数量
						int num = userIntegral.getRestScore() / lowScore;
						System.out.println("--数量：" + num);
						
						integral = new UserIntegral();
						integral.setUid(userIntegral.getUid());
						integral.setTitle("兑换10元现金红包（" + num + "个）");
						//收支类型为支出
						integral.setIncomeType("1");
						//支出方向为红包
						integral.setSource("11");
						//扣减分数
						integral.setScore(lowScore * num);
						integral.setRecordTime(DateUtils.getSysDate());
						
						userIntegralService.save(integral);
					}
				}
			}
			
			return "积分兑换成功！";
		} catch(Exception e){
			logger.error("--用户积分兑换出现异常！", e);
			
			return "积分兑换失败！";
		}
	}
}
